import React, { useState, useEffect } from 'react';
import { Row, Col, Card, List, Typography, Statistic, Tag, Spin } from 'antd';
import { FileOutlined, FolderOutlined, TagOutlined, EyeOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getKnowledgeList } from '../../api/knowledge';
import { getUserStats } from '../../api/user';
import { getHotTags } from '../../api/tag';

const { Title, Paragraph } = Typography;

const HomePage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [recentKnowledge, setRecentKnowledge] = useState([]);
  const [stats, setStats] = useState({
    knowledgeCount: 0,
    categoryCount: 0,
    tagCount: 0,
    storageUsed: 0,
    storageLimit: 1024 * 1024 * 1024, // 默认1GB
  });
  const [hotTags, setHotTags] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        // 获取最近知识
        const knowledgeRes = await getKnowledgeList({
          page: 1,
          size: 5,
          sortBy: 'updatedAt',
          sortOrder: 'desc',
        });
        setRecentKnowledge(knowledgeRes.items);

        // 获取统计信息
        const statsRes = await getUserStats();
        setStats(statsRes);

        // 获取热门标签
        const tagsRes = await getHotTags(10);
        setHotTags(tagsRes);
      } catch (error) {
        console.error('获取首页数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // 格式化存储空间
  const formatStorage = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  };

  // 计算存储空间使用百分比
  const storagePercent = Math.round((stats.storageUsed / stats.storageLimit) * 100);

  return (
    <div>
      <Title level={2}>欢迎使用个人知识管理系统</Title>
      <Paragraph>高效管理您的知识资源，提升学习和工作效率</Paragraph>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
        </div>
      ) : (
        <>
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="知识总数"
                  value={stats.knowledgeCount}
                  prefix={<FileOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="分类总数"
                  value={stats.categoryCount}
                  prefix={<FolderOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="标签总数"
                  value={stats.tagCount}
                  prefix={<TagOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="存储空间"
                  value={formatStorage(stats.storageUsed)}
                  suffix={`/ ${formatStorage(stats.storageLimit)} (${storagePercent}%)`}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
            <Col xs={24} md={16}>
              <Card title="最近更新的知识">
                <List
                  dataSource={recentKnowledge}
                  renderItem={(item: any) => (
                    <List.Item
                      actions={[<span><EyeOutlined /> {item.viewCount || 0}</span>]}
                    >
                      <List.Item.Meta
                        title={<Link to={`/knowledge/${item.id}`}>{item.title}</Link>}
                        description={item.description || '无描述'}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
            <Col xs={24} md={8}>
              <Card title="热门标签">
                <div>
                  {hotTags.map((tag: any) => (
                    <Tag 
                      key={tag.id} 
                      color={tag.color || '#108ee9'}
                      style={{ margin: '0 8px 8px 0' }}
                    >
                      <Link to={`/knowledge?tag=${tag.name}`}>{tag.name} ({tag.count})</Link>
                    </Tag>
                  ))}
                </div>
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default HomePage;